package com.mp.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mp.core.utils.*;
import com.mp.core.utils.common.NettyCommon;
import com.mp.enums.ActionEnum;
import com.mp.enums.ToSendEnum;
import com.mp.pojo.*;
import com.mp.pojo.BO.BetBO;
import com.mp.pojo.BO.BetDetailBO;
import com.mp.pojo.Query.BetDetailQuery;
import com.mp.pojo.Query.BetQuery;
import com.mp.pojo.Query.WebsiteLoginQuery;
import com.mp.pojo.Query.WebsiteUserQuery;
import com.mp.pojo.VO.WebsiteUrlVO;
import com.mp.pojo.VO.WebsiteUserVO;
import com.mp.pojo.VO.WebsiteVO;
import com.mp.service.*;
import io.swagger.annotations.*;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.params.ClientPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author jack
 * @data 2019-08-22 10:27
 */
@Api(value = "站点api")
@RestController
@RequestMapping("/api/website")
public class WebsiteApi {

    @Autowired
    private AdminService adminService;

    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private WebsiteUserService websiteUserService;

    @Autowired
    private WebsiteUrlService websiteUrlService;

    @Autowired
    private GameKeyCodeService gameKeyCodeService;
    
    @Autowired
    private GameService gameService;

    @Autowired
    private WebsiteFlyRecordService websiteFlyRecordService;

    @Autowired
    private NettyCommon nettyCommon;


    @Autowired
    private WebsiteGameService websiteGameService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public static final String APP_ID = "17055246";
    public static final String API_KEY = "nGl3pA98EK84TooDktMLet3g";
    public static final String SECRET_KEY = "yo7WvbGnGbPGo7BId1wP6SrSTZywQORW";

    private String cookie = "";

//
//    {
//        "lottery":"PCEGG",
//            "drawNumber":"969969",
//            "bets":[
//        {
//            "game":"DS",
//                "contents":"D",
//                "amount":1,
//                "odds":1.95,
//                "title":""
//        }
//    ],
//        "ignore":false
//    }

    @PostMapping("/bet")
    public Object bet(@RequestBody @Valid BetQuery betQuery) throws IOException {

        logger.error(JsonUtils.objectToJson(betQuery));

        //根据管理员账号获取对应的website账号信息，与站点url status为1的url
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getAccount,betQuery.getAccount());
        Admin admin = adminService.getOne(adminLambdaQueryWrapper);
        if (admin == null) {
            return MrdJsonResult.build503("该用户不存在");
        }
        WebsiteUrl websiteUrl = websiteUrlService.getOneByAdminId(admin.getId());


        boolean isRrun = true;
        String cause = "";
        String status = "";
        //先获取用户资料，若获取不到 走重登方法获取到最新的cookie
        if (websiteUrl == null) {
            isRrun = false;
            cause = "未登陆网盘账号";
            logger.warn("未登陆网盘账号");
        }
        String accoutResult = getAccount(websiteUrl.getData());
        if (StringUtils.isBlank(accoutResult)) {
            boolean flag = reLogin(websiteUrl.getWebsiteUserId());
            if (flag) {
                websiteUrl = websiteUrlService.getOneByAdminId(admin.getId());
            } else {
                isRrun = false;
                cause = "自动重登失败";
                logger.warn("自动重登失败");

            }
        }

        WebsiteUser websiteUser = websiteUserService.getById(websiteUrl.getWebsiteUserId());

        //            1 根据游戏code获取游戏键code
        LambdaQueryWrapper<Game> gameLambdaQueryWrapper = new LambdaQueryWrapper<>();
        gameLambdaQueryWrapper.eq(Game::getCode,betQuery.getLottery());

        Game selectGame = gameService.getOne(gameLambdaQueryWrapper);

        LambdaQueryWrapper<WebsiteGame> websiteGameLambdaQueryWrapper = new LambdaQueryWrapper<>();
        websiteGameLambdaQueryWrapper.eq(WebsiteGame::getGameId,selectGame.getId())
                .eq(WebsiteGame::getWebsiteId, websiteUser.getWebsiteId());

        WebsiteGame selectWebsiteGame = websiteGameService.getOne(websiteGameLambdaQueryWrapper);

        if (selectGame == null) {
            isRrun = false;
            cause = "该游戏code不存在";
            logger.warn("该游戏code不存在");
        }

        if (isRrun) {
            String bettUrl = websiteUrl.getUrl() + "/member/bet";

            LambdaQueryWrapper<GameKeyCode> gameKeyCodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            gameKeyCodeLambdaQueryWrapper.eq(GameKeyCode::getGameKeyId,selectGame.getGameKeyId())
                    .select(GameKeyCode::getName,GameKeyCode::getCode);
            List<Map<String, Object>> maps = gameKeyCodeService.listMaps(gameKeyCodeLambdaQueryWrapper);
            HashMap<String, String> keyCodeMap = new HashMap<>();
            maps.forEach(map -> {
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                String key = "";
                String value = "";
                while (it.hasNext()) {

                    Map.Entry<String, Object> next = it.next();
                    if (next.getKey().equals("name")) {
                        key = next.getValue().toString();
                    }else if (next.getKey().equals("code")) {
                        value = next.getValue().toString();
                    }
                }
                keyCodeMap.put(key, value);
            });
            // 2将betQuery 转为对应的BO
            BetBO betBO = new BetBO();
            DiyBeanUtils.copyProperties(betQuery,betBO);
            // 2.1将bes循环，获取对应的下注code,下注数量 添加bet 到bo
            boolean getOddsIsOk = true;
            ArrayList<BetDetailBO> betDetailBOS = new ArrayList<>();
            for (BetDetailQuery bet : betQuery.getBets()) {
                String name = keyCodeMap.get(bet.getName());
                if (name != null) {
                    BetDetailBO betDetailBO = new BetDetailBO();
                    betDetailBO.setAmount(bet.getAmount());
                    String[] split = name.split("_");
                    betDetailBO.setGame(split[0]);
                    betDetailBO.setContents(split[1]);

                    //获取赔率
                    try {
                        String result = odds(betQuery.getLottery(), split[0],websiteUrl.getData());
                        System.out.println("获取赔率:" + result);
                        String odds = JSONObject.parseObject(result).get(name).toString();
                        betDetailBO.setOdds(odds);
                    } catch (Exception e) {
                        getOddsIsOk =false;
                        logger.error("获取动态赔率失败");

                        WebsiteFlyRecord websiteFlyRecord = new WebsiteFlyRecord();
                        websiteFlyRecord.setAmount(bet.getAmount());
                        websiteFlyRecord.setDetails(bet.getName());
                        websiteFlyRecord.setIsNot(2);
                        websiteFlyRecord.setFailLog("对方已封盘");
                        websiteFlyRecord.setNumber(betQuery.getDrawNumber());
                        websiteFlyRecord.setWebsiteGameId(selectWebsiteGame.getId());
                        websiteFlyRecord.setWebsiteUserId(websiteUrl.getWebsiteUserId());
                        websiteFlyRecordService.save(websiteFlyRecord);
                    }
                    betDetailBO.setAmount(bet.getAmount());
                    betDetailBOS.add(betDetailBO);
                }
            }
            if (!getOddsIsOk) {
                JSONObject result = new JSONObject();
                result.put("state", 2);
                result.put("game", selectGame.getCode());
                nettyCommon.wsWrite200(websiteUser.getId(),result, ActionEnum.FLY_RECORD, ToSendEnum.TO_SENDER);
                return MrdJsonResult.ok();
            }
            betBO.setBets(betDetailBOS);
//            System.out.println(JsonUtils.objectToJson(betBO));
            String result = HttpClientUtil.doPostJson(bettUrl,JsonUtils.objectToJson(betBO),websiteUrl.getData());
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            status = jsonObject.get("status").toString();
        }

        ArrayList<WebsiteFlyRecord> websiteFlyRecords = new ArrayList<>();
        WebsiteFlyRecord websiteFlyRecord = new WebsiteFlyRecord();
        if (!isRrun){
            websiteFlyRecord.setIsNot(2);
            websiteFlyRecord.setFailLog(cause);
        }else {
            if (status.equals("0")){
                websiteFlyRecord.setIsNot(1);
            }else if (status.equals("2")){
                websiteFlyRecord.setIsNot(2);
                websiteFlyRecord.setFailLog("飞单参数不正确");
            }else if (status.equals(1)){
                websiteFlyRecord.setIsNot(2);
                websiteFlyRecord.setFailLog("未知错误");
            }
        }
        websiteFlyRecord.setNumber(betQuery.getDrawNumber());
        websiteFlyRecord.setWebsiteGameId(selectWebsiteGame.getId());
        websiteFlyRecord.setWebsiteUserId(websiteUrl.getWebsiteUserId());
        //添加记录
        for (BetDetailQuery bet : betQuery.getBets()) {
            WebsiteFlyRecord saveFlyRecord = new WebsiteFlyRecord();
            DiyBeanUtils.copyProperties(websiteFlyRecord, saveFlyRecord);
            saveFlyRecord.setAmount(bet.getAmount());
            saveFlyRecord.setDetails(bet.getName());
            websiteFlyRecords.add(saveFlyRecord);
        }
        JSONObject result = new JSONObject();
        result.put("state", websiteFlyRecord.getIsNot());
        result.put("game", selectGame.getCode());
        nettyCommon.wsWrite200(websiteUser.getId(),result, ActionEnum.FLY_RECORD, ToSendEnum.TO_SENDER);
        websiteFlyRecordService.saveBatch(websiteFlyRecords);

        //
        return MrdJsonResult.ok();

    }


     /**
     * 获取游戏赔率
     * @param
     * @return
     * @throws IOException
     */
    public String odds(String lottery, String games, String cookie) throws IOException {
        String accountUrl = "https://5535393761-rrl.cp168.ws/member/odds?lottery=" + lottery +"&games=" + games +"&_=" + System.currentTimeMillis();
        System.out.println(accountUrl);
        JSONObject result = doGet(accountUrl, cookie);
        return result.get("data").toString();


    }


    @ApiOperation(value = "获取网点信息",response = WebsiteVO.class)
    @GetMapping("/getWebsiteList")
    @ApiImplicitParams(
    @ApiImplicitParam(name = "adminId",value = "管理员id",required = true, dataType = "int")
    )
    public JSONObject getWebsiteList(Integer adminId) throws IOException {
        // 获取管理员信息
        Admin selectAdmin = adminService.getById(adminId);
        if (selectAdmin == null){
            return MrdJsonResult.build503("该管理员不存在");
        }
        //1 获取站点list
        List<Website> websiteList = websiteService.list();
        List<WebsiteVO> websiteVoList = DiyBeanUtils.entityListToModelList(websiteList, WebsiteVO.class);
        //1.1 根据站点获取网站list,站点用户信息
        if (websiteVoList !=null && websiteList.size() > 0){
            websiteVoList.forEach(w -> {
                LambdaQueryWrapper<WebsiteUser> websiteUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                websiteUserLambdaQueryWrapper.eq(WebsiteUser::getAdminId, adminId)
                        .eq(WebsiteUser::getWebsiteId, w.getId());
                WebsiteUser websiteUser = websiteUserService.getOne(websiteUserLambdaQueryWrapper);
                WebsiteUserVO websiteUserVO = new WebsiteUserVO();
                if (websiteUser != null){
                    BeanUtils.copyProperties(websiteUser,websiteUserVO);
                    w.setWebsiteUser(websiteUserVO);
                }
                //1.2获取 站点下所有网址（包括状态）
                if (websiteUser != null) {
                    LambdaQueryWrapper<WebsiteUrl> websiteUrlLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    websiteUrlLambdaQueryWrapper.eq(WebsiteUrl::getWebsiteUserId, websiteUser.getId());
                    List<WebsiteUrl> websiteUrlList = websiteUrlService.list(websiteUrlLambdaQueryWrapper);
                    List<WebsiteUrlVO> websiteUrlVoList = DiyBeanUtils.entityListToModelList(websiteUrlList, WebsiteUrlVO.class);
                    w.setWebsiteUrlList(websiteUrlVoList);
                }

            });
        }
        return MrdJsonResult.ok(websiteVoList);
    }

    @ApiOperation(value = "站点用户保存或顶号")
    @PostMapping("/saveOrUpdateLogin")
    public JSONObject saveOrUpdateLogin(@RequestBody @Valid WebsiteUserQuery websiteUserQuery){
        //判断站点id是否存在
        if (websiteService.getById(websiteUserQuery.getWebsiteId()) == null){
            return MrdJsonResult.build503("站点id不存在");
        }
        //判断管理员id是否存在
        Admin selectAdmin = adminService.getById(websiteUserQuery.getAdminId());
        if (selectAdmin == null){
            return MrdJsonResult.build503("该管理员不存在");
        }
        String error = websiteUserService.saveOrUpdate(websiteUserQuery);
        if (StringUtils.isNotBlank(error)) {
            MrdJsonResult.build503(error);
        }
        return MrdJsonResult.ok();
    }
    @ApiOperation(value = "站点用户保存或顶号2")
    @PostMapping("/saveOrUpdateLogin2")
    public JSONObject saveOrUpdateLogin2( @Valid WebsiteUserQuery websiteUserQuery){
        //判断站点id是否存在
        if (websiteService.getById(websiteUserQuery.getWebsiteId()) == null){
            return MrdJsonResult.build503("站点id不存在");
        }
        //判断管理员id是否存在
        Admin selectAdmin = adminService.getById(websiteUserQuery.getAdminId());
        if (selectAdmin == null){
            return MrdJsonResult.build503("该管理员不存在");
        }
        String error = websiteUserService.saveOrUpdate(websiteUserQuery);
        if (StringUtils.isNotBlank(error)) {
            MrdJsonResult.build503(error);
        }
        return MrdJsonResult.ok();
    }



    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public JSONObject login(@Valid WebsiteLoginQuery websiteLoginQuery) throws IOException {
       try {
           // 判断登录信息是否已保存


           // 获取站点信息
           WebsiteUrl websiteUrl = websiteUrlService.getById(websiteLoginQuery.getWebsiteUrlId());
           if (websiteUrl == null) {
               return MrdJsonResult.build503("网址urlid不存在");
           }

           WebsiteUser websiteUser = websiteUserService.getById(websiteUrl.getWebsiteUserId());

           if (websiteUser == null) {
               return MrdJsonResult.build503("websiteUser 不存在");
           }

           if (!websiteLoginQuery.getAdminId().equals(websiteUser.getAdminId())) {
               return MrdJsonResult.build503("adminId 与登录信息不匹配!");
           }

           // 根据站点信息获取 登录路由(金峰)
           if (websiteUser.getWebsiteId().equals(1)) {
               String code = getCode();
               //获取金峰登录路由
               String dataUrl = websiteUrl.getUrl()+ "/login?type=1&account=" +websiteUser.getAccount() +"&password=" +  websiteUser.getPassword() +"&code=" + code;

//        String result = doGet(dataUrl).getResponseBodyAsString();
               JSONObject jsonObject = doGet(dataUrl, cookie);
               if (jsonObject.get("data").toString().contains("用户协议")) {
                   //保存登录信息 先将其他网站状态设为2
                   LambdaUpdateWrapper<WebsiteUrl> websiteUrlLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                   websiteUrlLambdaUpdateWrapper.eq(WebsiteUrl::getWebsiteUserId, websiteUser.getId())
                           .set(WebsiteUrl::getStatus,2);
                   websiteUrlService.update(websiteUrlLambdaUpdateWrapper);


                   websiteUrl.setData(jsonObject.get("cookie").toString());
                   websiteUrl.setStatus(1);
                   websiteUrlService.updateById(websiteUrl);
                   return MrdJsonResult.ok();
               }else if (jsonObject.get("data").toString().contains("账号或密码错误")){
                   System.out.println(jsonObject.get("data").toString());
                   return MrdJsonResult.build(889,"账号或密码错误");
               } else{
                   return MrdJsonResult.build(888,"验证码错误，请重新输入");
               }
           } else {
               return MrdJsonResult.build(888,"登录失败，请重新登录");
           }
       }catch (Exception e){
           return MrdJsonResult.build(888,"登录失败,请重新登录");
       }

    }


    @ApiOperation(value = "获取用户信息")
    @GetMapping("/account")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "websiteUrlId",value = "网点url主键id",required = true, dataType = "int")
    )
    public Object account(Integer websiteUrlId) throws IOException {
        String accountUrl = "https://5535393761-rrl.cp168.ws/member/accounts?_=" + System.currentTimeMillis();


        WebsiteUrl websiteUrl = websiteUrlService.getById(websiteUrlId);
        if (websiteUrl == null) {
            return MrdJsonResult.build503("该参数不对！");
        }
        PostMethod postMethod = doPost(accountUrl, null, websiteUrl.getData());
        if (postMethod.getStatusCode() == 200) {

            String resultStr = postMethod.getResponseBodyAsString();
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject result = new JSONObject();
                List<Map> maps = JsonUtils.jsonToList(resultStr, Map.class);
                Map<String,Object> map = maps.get(0);
                Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> next = it.next();
                    System.out.println(next.getKey() + " : " + next.getValue());
                    result.put(next.getKey(), next.getValue());
                }
                QueryWrapper<WebsiteFlyRecord> websiteFlyRecordQueryWrapper = new QueryWrapper<>();
                websiteFlyRecordQueryWrapper
                        .eq("website_user_id", websiteUrl.getWebsiteUserId())
                        .apply("date_format(create_time,'%y-%m-d') <= {0}", DateUtils.DateToString(new Date(), DateUtils.formatStr_yyyyMMdd))
                        .eq("is_not", 1)
                        .select("ifnull(sum(amount),0) as amountToday");
                Map<String, Object> amountTodayMap = websiteFlyRecordService.getMap(websiteFlyRecordQueryWrapper);

                result.put("amountToday", amountTodayMap.get("amountToday"));

                return MrdJsonResult.ok(result);

            } else {
                return MrdJsonResult.build(201,"请重新登录");
            }
        } else {
            logger.error(postMethod.getResponseBodyAsString());
            return MrdJsonResult.build(201,"请重新登录");
        }



//        JSONObject jsonObject = JSONObject.parseObject(result);
//        jsonObject.getJSONArray()
//        betting 当前使用
//        balance 剩余
//        result 网盘流水

    }


    public String getAccount(String cookie) throws IOException {
        String accountUrl = "https://5535393761-rrl.cp168.ws/member/accounts?_=" + System.currentTimeMillis();
        String result = doPost(accountUrl,null,cookie).getResponseBodyAsString();
        return result;
    }


    public boolean reLogin(Integer websiteUserId){
        try {
            WebsiteUser selectWebsiteUser = websiteUserService.getById(websiteUserId);
            if (selectWebsiteUser != null) {
                // 根据站点信息获取 登录路由(金峰)
                if (!selectWebsiteUser.getWebsiteId().equals(1)) {
                    //目前只支持金峰登录
                    return false;
                }
                //获取对应网点下的website_url list
                LambdaQueryWrapper<WebsiteUrl> websiteUrlLambdaQueryWrapper = new LambdaQueryWrapper<>();
                websiteUrlLambdaQueryWrapper.eq(WebsiteUrl::getWebsiteUserId, selectWebsiteUser.getId());
                List<WebsiteUrl> websiteUrls = websiteUrlService.list(websiteUrlLambdaQueryWrapper);
                if (websiteUrls != null && websiteUrls.size() > 0) {
                    for (WebsiteUrl wu : websiteUrls) {
                        Integer n = 1;
                        while (n< 6) {
                            //true为登录成功 false n累加  n次后切换登录地址
                            JSONObject result = forLogin(selectWebsiteUser, wu);
                            if ((Boolean) result.get("status")){

                                //保存登录信息 先将其他网站状态设为2
                                LambdaUpdateWrapper<WebsiteUrl> websiteUrlLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                websiteUrlLambdaUpdateWrapper.eq(WebsiteUrl::getWebsiteUserId, wu.getWebsiteUserId())
                                        .set(WebsiteUrl::getStatus,2);
                                websiteUrlService.update(websiteUrlLambdaUpdateWrapper);
                                //登录成功记录 websitUrlUser 并保存cookie


                                wu.setData(result.get("data").toString());
                                wu.setStatus(1);
                                websiteUrlService.updateById(wu);




                                return true;
                            }
                            n++;
                            System.out.println("地址为:" + wu.getUrl() + " 第次" + n + " 失败");
                        }


                    }
                }
            }
        }catch (Exception e){
            logger.error("自动登录失败",e);
        }

        return false;
    }

    private JSONObject forLogin(WebsiteUser selectWebsiteUser, WebsiteUrl wu) {
        JSONObject result = new JSONObject();

        String code = "";
        //获取验证码
        try {
            code = getCode();
            System.out.println("验证码为:" + code);
        } catch (IOException e) {
            System.out.println("获取验证码失败");
        }
        //获取金峰登录路由
        String dataUrl = wu.getUrl()+ "/login?type=1&account=" +selectWebsiteUser.getAccount() +"&password=" +  selectWebsiteUser.getPassword() +"&code=" + code;
        String data = null;
        try {
            data = doGet(dataUrl).getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            result.put("status", false);
            return result;
        }
        if (data.contains("用户协议")) {
            result.put("status", true);
            result.put("data",cookie);
            return result;
        }else {
            System.out.println("登录失败");
            result.put("status", false);
            return result;
        }
    }


    public String getCode() throws IOException {

        // 登陆 Url
        String loginUrl = "https://5535393761-rrl.cp168.ws/code?_=" + System.currentTimeMillis();

        byte[] data = doGet(loginUrl).getResponseBody();

        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);


        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");

        String code = "";

        // 调用接口
        org.json.JSONObject res = client.basicGeneral(data, options);
        String wordsResult = res.toString();
        if (StringUtils.isNotBlank(wordsResult)){
            try {
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(wordsResult);
                JSONArray words_result = jsonObject.getJSONArray("words_result");
                String index = words_result.get(0).toString();
                com.alibaba.fastjson.JSONObject result = JSON.parseObject(index);
                code = result.getString("words");
            }catch (Exception e) {
                  logger.warn("百度code解析错误");
                code = "";
            }
            logger.info("getCode:" +code);
        }
        return code;
    }


    private GetMethod doGet(String dataUrl) throws IOException {
        HttpClient httpClient = new HttpClient();

        GetMethod getMethod = new GetMethod(dataUrl);
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
        if (StringUtils.isNotBlank(cookie)) {
            getMethod.setRequestHeader("cookie", cookie);
        }
        int statusCode = httpClient.executeMethod(getMethod);

        // 获取Cookie
        Cookie[] cookies = httpClient.getState().getCookies();
        StringBuffer tmpcookies = new StringBuffer();
        for (Cookie c : cookies) {
            tmpcookies.append(c.toString() + ";");
            System.out.println("cookies = "+c.toString());
        }
        if (StringUtils.isNotBlank(tmpcookies.toString())){
            cookie = tmpcookies.toString();
        }
        return getMethod;
    }



    private JSONObject doGet(String dataUrl, String cookie) throws IOException {
        JSONObject result = new JSONObject();
        HttpClient httpClient = new HttpClient();

        GetMethod getMethod = new GetMethod(dataUrl);
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
        if (StringUtils.isNotBlank(cookie)) {
            getMethod.setRequestHeader("cookie", cookie);
        }
        httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        int statusCode = httpClient.executeMethod(getMethod);


        result.put("code",statusCode);
        // 获取Cookie
        Cookie[] cookies = httpClient.getState().getCookies();
        StringBuffer tmpcookies = new StringBuffer();
        for (Cookie c : cookies) {
            tmpcookies.append(c.toString() + ";");
            System.out.println("cookies = "+c.toString());
        }
        if (StringUtils.isNotBlank(tmpcookies.toString())){
            result.put("cookie",tmpcookies.toString());
        }
        result.put("data",getMethod.getResponseBodyAsString());
        return result;
    }

    private PostMethod doPost(String dataUrl, HashMap<String,String> map, String cookie) throws IOException {
        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(dataUrl);

        if (map != null){
            ArrayList<NameValuePair> valuePairList = new ArrayList<>();
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()){
                Map.Entry<String, String> next = it.next();
                valuePairList.add(new NameValuePair(next.getKey(), next.getValue()));
            }

            postMethod.setRequestBody(valuePairList.toArray(new NameValuePair[valuePairList.size()]));
        }
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
        if (StringUtils.isNotBlank(cookie)) {
            postMethod.setRequestHeader("cookie", cookie);
        }
        httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        int statusCode = httpClient.executeMethod(postMethod);
        // 获取Cookie
        Cookie[] cookies = httpClient.getState().getCookies();
        StringBuffer tmpcookies = new StringBuffer();
        for (Cookie c : cookies) {
            tmpcookies.append(c.toString() + ";");
            System.out.println("cookies = "+c.toString());
        }
        if (StringUtils.isNotBlank(tmpcookies.toString())){
            cookie = tmpcookies.toString();
        }
        return postMethod;
    }
}
